package top.eggcode.template.dict;

import lombok.AllArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import top.eggcode.common.exception.ApplicationException;
import top.eggcode.common.mvc.Result;
import top.eggcode.component.dict.Translate;
import top.eggcode.component.dict.Translator;
import top.eggcode.component.query.model.PageList;

import java.util.List;

/**
 * Title:
 * Description: TODO
 * Date: 2021/6/24 11:10
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Aspect
@Component
@AllArgsConstructor
public class ViewTranslateHandler {

    @Pointcut("@annotation(top.eggcode.component.dict.Translate)")
    public void pointcut() {
    }

    /**
     * 视图数据翻译
     * 目前仅支持Page对象
     *
     * @param point 切入点
     * @param anno  注解
     * @return 视图数据
     * @throws Throwable 异常
     */
    @Around("pointcut() && @annotation(anno)")
    public Object doAround(ProceedingJoinPoint point, Translate anno) throws Throwable {

        Object proceed = point.proceed();
        if (!(proceed instanceof Result)) {
            throw new ApplicationException("handler 方法返回的不是PackageDTO实例！");
        }
        Result<?> dto = (Result<?>) proceed;

        Object pageObject = dto.getData();

        PageList<?> page = (PageList<?>) pageObject;
        List<?> viewList = page.getList();
        viewList.forEach(Translator::start);
        return proceed;
    }
}
